
import { getToken, setToken, removeToken, getOperator, setOperator, removeOperator } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    username: '',
    operator: getOperator() ? JSON.parse(getOperator()) : undefined,
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_OPERATOR: (state, operator) => {
    state.operator = operator
  },
}

const actions = {

  setToken({ commit }, userInfo) {
    const { username, token, operator, operator_name } = userInfo
    console.log(userInfo);
    commit('SET_TOKEN', token);
    commit('SET_USERNAME', username);
    if (operator) {
      const operator_data = {
        operator,
        operator_name,
      }
      commit('SET_OPERATOR', operator_data);
      setOperator(JSON.stringify(operator_data));
    }

    setToken(token);

  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken();
      removeOperator();
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

